#!/usr/bin/perl

use DBI;

# SSO update login time for user  - possibly not needed ...

sub _update_login_time($) {
my $user=shift;

	my $fc=substr($user,0,1);
	if(! -f "/tcb/files/auth/$fc/$user") {
		return "NO_USER";
	}
	my @L=();
	my $fd;
	open($fd,"/tcb/files/auth/$fc/$user") or return "FAIL Could not open file";
	@L=<$fd>; close($fd);
	my $t=time;

	#################################################################
	# Set the u_suclog entry, or add if it is is not present.	#
	#################################################################
	my $found=0;
	for (@L) {
		if(/u_suclog#(\d+)/) {
			my ($d)=(/u_suclog#(\d+)/);
			$found=1;
			s/u_suclog#(\d+)/u_suclog#$t/;
			last;
		}
	}
	#################################################################
	# If we have not found the n_numunsuclog entry then we need to	#
	# add it. We add this to the last line, at the start though	#
	# the order should not matter!					#
	#################################################################
	if(! $found) {
		my $l=$L[$#L-1];
		$l =~ s/^\s+//;
		$l="\t:u_suclog#$t$l";
		$L[$#L-1]=$l;
	}

	#################################################################
	# Now we look for a u_numunsuclog#N entry and remove it since	#
	# we've managed to log in successfully.				#
	#################################################################
	$found=0;
	for (@L) {
		s/u_numunsuclog#(\d+)://;
	}

	#################################################################
	# Write the results back out to the file.			#
	#################################################################
	open($fd,">/tcb/files/auth/$fc/$user.tmp") or return "FAIL Could not open tmp file";
	print $fd $_ foreach(@L);
	close($fd);
	rename("/tcb/files/auth/$fc/$user","/tcb/files/auth/$fc/$user.old") or
		return "FAIL Could not rename file.";
	rename("/tcb/files/auth/$fc/$user.tmp","/tcb/files/auth/$fc/$user") or
		return "FAIL Could not renmae file.";
	unlink("/tcb/files/auth/$fc/$user.old");
	return "OK";
}

if(exists($::ENV{HTTP_SMUSER}) && length($::ENV{HTTP_SMUSER})) {
	$x=lc($::ENV{HTTP_SMUSER});
	$x =~ s!^.*\\\\!!g;
	$x =~ s!^.*\\!!g;
	my $dir="/tmp";
	if(exists($::ENV{GRI_MACRO_CACHE})) {
		$dir=$::ENV{GRI_MACRO_CACHE};
	}
	my $dbname="$dir/get_sso_id_cache.db";
	my $empty=0;
	$empty=1 if ! -f $dbname;
	my $dbh=DBI->connect("dbi:SQLite:dbname=$dbname","","",
                {RaiseError => 0,PrintError => 0,AutoCommit => 1});
	if($empty) {
		$dbh->do("CREATE TABLE user_updates(user PRIMARY KEY,ctime)");
	}
	my $hr=$dbh->selectrow_hashref("SELECT * FROM user_updates WHERE user = '$x';");
	my $ct=time;
	if(defined($hr) && exists($hr->{ctime}) && defined($hr->{ctime})) {
		if($hr->{ctime}+3600<$ct) {
			$dbh->do("INSERT OR REPLACE INTO user_updates (user,ctime) VALUES ('$x','$ct');");
			_update_login_time($x);
		}
	} else {
		$dbh->do("INSERT OR REPLACE INTO user_updates (user,ctime) VALUES ('$x','$ct');");
		_update_login_time($x);
	}
	$dbh->disconnect();
	print "$x\n";
}
exit(0);
